import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export interface UserInfo {
  id: string;
  username: string;
  email: string;
  avatar?: string;
}

export const useAuthStore = defineStore(
  'auth',
  () => {
    const token = ref<string | null>(null);
    const userInfo = ref<UserInfo | null>(null);

    const isLoggedIn = computed(() => {
      return !!token.value && !!userInfo.value;
    });

    const setToken = (newToken: string) => {
      token.value = newToken;
    };

    const setUserInfo = (info: UserInfo) => {
      userInfo.value = info;
    };

    const login = (tokenValue: string, user: UserInfo) => {
      setToken(tokenValue);
      setUserInfo(user);
    };

    const logout = () => {
      token.value = null;
      userInfo.value = null;
      // 清除本地存储
      uni.removeStorageSync('token');
      uni.removeStorageSync('userInfo');
    };

    return {
      token,
      userInfo,
      isLoggedIn,
      setToken,
      setUserInfo,
      login,
      logout,
    };
  },
  {
    persist: {
      key: 'auth-store',
      paths: ['token', 'userInfo'],
    },
  }
);